import { Strategy, IStrategyOptions } from "passport-local"
import { PassportStrategy } from '@nestjs/passport';
import { InjectModel } from "nestjs-typegoose";
import { BadGatewayException } from "@nestjs/common";
import { compareSync } from "bcryptjs"
import { ModelType } from "@typegoose/typegoose/lib/types";
import { WebUserModel } from "src/mongodb/models/userModel/webUser.models";


/* 登录策略 */
export class LocalStrategy extends PassportStrategy(Strategy, "local") {
    constructor(@InjectModel(WebUserModel) private readonly userModel: ModelType<WebUserModel>) {
        super({
            usernameField: "name",
            passwordField: "password"
        } as IStrategyOptions)
    }

    async validate(name: string, password: string) {
        const user = await this.userModel.findOne({ name, status: true }).select("+password")
        if (!user) {
            throw new BadGatewayException("该用户还未注册或者被冻结")
        }
        if (!compareSync(password, user.password)) {
            throw new BadGatewayException("密码不正确")
        }
        return user
    }

}